<?php
include("utils.php");
if($_SESSION['siteuserId']=="")
{
	header("location:start.php");
}
if($_POST['mode']=="change_status")
{
	change_status();
}
else
{
	main_content("main();");
}


function main()
{

if($_SESSION['languageId']!="")
{
	$languageId=$_SESSION['languageId'];
}
else
{
	$languageId='1';
}


$sql_details_summary="SELECT * FROM advertise_master AM ,advertise_details AD  where AM.advertiseId= AD.advertiseId and AM.siteuserId = '".$_SESSION['siteuserId']."'";
//echo $sql_details;


$query_details_summary=mysql_query($sql_details_summary);
$num_summary=mysql_num_rows($query_details_summary);

//  $query_site_name=mysql_query("select adSiteName from adsite_master where siteuserId='".$_SESSION['siteuserId']."' and langId='".$languageId."'");


if($_REQUEST['mode']=='publisher_statistics')
{

$today=date("Y-m-d");
if($_REQUEST['ad_site']!='' && $_REQUEST['ad_type']=='' && $_REQUEST['ad_status']=='')
{
	
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' and AM.startDate > '".$_REQUEST['start_date']."' AND AM.endDate < '".$_REQUEST['end_date']."' and SM.adSiteUrl = '".$_REQUEST['ad_site']."'";
}
else if($_REQUEST['ad_site']=='' && $_REQUEST['ad_status']=='' && $_REQUEST['ad_type']!='')
{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' and AM.startDate > '".$_REQUEST['start_date']."' AND AM.endDate < '".$_REQUEST['end_date']."' and ASD.adspaceType = '".$_REQUEST['ad_type']."'";
}
else if($_REQUEST['ad_site']=='' && $_REQUEST['ad_type']=='' && $_REQUEST['ad_status']!='')
{
	if($_REQUEST['ad_status']=='ending')
	{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' and  AM.endDate = '".$today."'";
	}
	else if($_REQUEST['ad_status']=='expired')
	{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' and  AM.endDate < '".$today."'";
	}

}
else if($_REQUEST['ad_site']!='' && $_REQUEST['ad_type']!='' && $_REQUEST['ad_status']=='')
{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' and AM.startDate > '".$_REQUEST['start_date']."' AND AM.endDate < '".$_REQUEST['end_date']."' and SM.adSiteUrl = '".$_REQUEST['ad_site']."' AND ASD.adspaceType = '".$_REQUEST['ad_type']."'";
}
else if($_REQUEST['ad_site']=='' && $_REQUEST['ad_type']!='' && $_REQUEST['ad_status']!='')
{
	if($_REQUEST['ad_status']=='ending')
	{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' AND AM.endDate = '".$today."' AND ASD.adspaceType = '".$_REQUEST['ad_type']."'";
	}
	else if($_REQUEST['ad_status']=='expired')
	{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' AND AM.endDate < '".$today."' AND ASD.adspaceType = '".$_REQUEST['ad_type']."'";
	}
}
else if($_REQUEST['ad_site']!='' && $_REQUEST['ad_type']=='' && $_REQUEST['ad_status']!='')
{
	if($_REQUEST['ad_status']=='ending')
	{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' AND AM.endDate = '".$today."' AND SM.adSiteUrl = '".$_REQUEST['ad_site']."'";
	}
	else if($_REQUEST['ad_status']=='expired')
	{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' AND AM.endDate < '".$today."' AND SM.adSiteUrl = '".$_REQUEST['ad_site']."'";
	}
}
else if($_REQUEST['ad_site']!='' && $_REQUEST['ad_type']!='' && $_REQUEST['ad_status']!='')
{
	if($_REQUEST['ad_status']=='ending')
	{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' AND AM.endDate = '".$today."' AND SM.adSiteUrl = '".$_REQUEST['ad_site']."' and ASD.adspaceType = '".$_REQUEST['ad_type']."'";
	}
	else if($_REQUEST['ad_status']=='expired')
	{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' AND AM.endDate < '".$today."' AND SM.adSiteUrl = '".$_REQUEST['ad_site']."' and ASD.adspaceType = '".$_REQUEST['ad_type']."'";
	}
}
else
{
	$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and  AM.siteuserId = '".$_SESSION['siteuserId']."' and AM.startDate > '".$_REQUEST['start_date']."' AND AM.endDate < '".$_REQUEST['end_date']."'";
}
if($_REQUEST['purchase_type']!='')
{
	if($_REQUEST['purchase_type']=='direct')
	{
		$sql_details.= "and AD.networkId = 0"; 
	}
	if($_REQUEST['purchase_type']=='network')
	{
		echo $sql_details.= "and AD.networkId > 0"; 
	}
}
}

else
{

  $sql_details="SELECT * FROM advertise_master AM ,advertise_details AD , adspace_master ADM ,adspace_details ASD , adsite_master SM where AM.advertiseId= AD.advertiseId and AD.adspaceId=ADM.adspaceId and ADM.adspaceId=ASD.adspaceId and AD.adsiteId=SM.adsiteId and AM.siteuserId = '".$_SESSION['siteuserId']."'";

//$sql_details="SELECT * FROM advertise_master AM ,advertise_details AD where AM.advertiseId= AD.advertiseId and AM.siteuserId = '".$_SESSION['siteuserId']."'";

	//echo $sql_details;
}
$query_details=mysql_query($sql_details);
$num=mysql_num_rows($query_details);
//echo $num;
?>
<link rel="stylesheet" href="css/ext-all.css" type="text/css" />
<link rel="stylesheet" href="css/xtheme-gray.css" type="text/css" />
<link rel="stylesheet" href="css/styles.css" type="text/css" />
<style type="text/css">
#holder {
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    -webkit-box-shadow: 0 1px 3px #666;
    background: #ddd url(images/bg.png);
    margin: 0 auto;
    width: 100%;
    height: 250px;
    text-align: center;
}
</style>
<script language="JavaScript">
function search_pub_statistics()
{
document.adspaces.mode.value="publisher_statistics";
document.adspaces.submit();
}
</script>
<!--<SCRIPT language=javascript src="calender/js/popcalendar.js"></SCRIPT>-->
<script language="javascript" type="text/javascript" src="JavaScripts/datetimepicker.js"></script>
<form name="adspaces" action="" method="POST" id="adspaces" onsubmit="return search_pub_statistics();">
<input type="hidden" name="mode" value=""><br />
<br />
<table width="90%" border="0" cellspacing="0" cellpadding="0" align="center">
<tr>
<td valign="top" align="center">
<table width="90%" border="0" cellspacing="0" cellpadding="0" align="center">
              <tr>
                <td valign="top" align="center"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0" >
                  <tr>
                    <td>&nbsp;</td>
                    <td><table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
                      <tr>
                        <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                              <td width="11"><img src="images/PinkBorderTopLeft.jpg" alt="" width="11" height="11"></td>
                              <td class="PinkBoxTopBg"><img src="images/spacer.gif" alt="" width="10" height="11"></td>
                              <td width="11"><img src="images/PinkBorderTopRight.jpg" alt="" width="11" height="11"></td>
                            </tr>
                        </table></td>
                      </tr>
                      <tr>
                        <td class="PinkTwosideBorder"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0">
<body id="tab2">
<ul id="tabnav">
<!--<li class="tab1"><a href="my_account.php?sid=<?php// echo $_REQUEST['sid'];?>">Summary</a></li>-->
<li class="tab1"><a href="advertiser_statistics.php">Today</a></li>
<li class="tab2"><a href="advertiser_custom_statistics.php">Custom</a></li>
</ul>
</body>
                            <tr>
                              <td class="BoxContent">
<!-- #########starts design ######### -->
<table id="spacesList" style="width:100%;margin-left:1px;position:relative" align="center" border="0" >

<tr>
    <td colspan="2" align="center" class="sky font-18" style="padding-bottom:20px;">
	Advertiser Statistics
	</td>
<?php
if($GLOBALS['err_msg']!="")
{
?>
<tr>
    <td colspan="2" align="center" class="font-11 latest_heading2" style="padding-bottom:10px;">
	<strong><?php echo $GLOBALS['err_msg'];?></strong>
	</td>
</tr>
<?php
}
?>
<?php
$current_date=date("Y-m-d");
//echo $current_date;
$explode_current_date=explode("-",$current_date);

$explode_next_year=$explode_current_date[0]+1;
$nextyear=$explode_next_year."-".date("m")."-".date("d");

$explode_previous_year=$explode_current_date[0]-1;
$previousyear=$explode_previous_year."-".date("m")."-".date("d");

$select_site="select * from ".SITEMASTER." where status='Y' order by adsiteId";
$exe_site=mysql_query($select_site);
//print_r(mysql_fetch_array($exe_site));die;
?>
<tr>
    <td style="text-align:left;white-space:nowrap;padding-bottom:10px;" colspan="" valign="middle">
        <span class="font-12 black advertise_tableTxt">
            <!--Show starts from:
            <input type="text" name="start_date" id="start_date" value="<?php echo $previousyear; ?>" class="InputBox" onClick="javascript:NewCal('start_date','yyyymmdd',false,24);" style="width:100;" maxlength="100" >&nbsp;to:&nbsp;
            <input type="text" name="end_date" id="end_date" value="<?php echo $nextyear; ?>" class="InputBox" onClick="javascript:NewCal('end_date','yyyymmdd',false,24);" style="width:100" maxlength="100">
            -->
            Site:
                <select id="ad_site" name="ad_site" class="InputBox" style="width: 100px;" maxlength="100">
                <!--<option value="">All</option>-->
                <?php
                $b=true;$fAd='';
                while($row_site=mysql_fetch_array($exe_site)){
                ?>
                    <option value="<?php echo $row_site['adsiteId']; ?>" <?php echo $_POST['ad_site']==$row_site['adsiteId']?"selected=\"selected\" ":''; ?>>
                        <?php echo $row_site['adSiteUrl']; ?>
                    </option>
                <?php
                    if($b){
                        $fAd=$row_site['adsiteId'];}
                    $b=false;
                }               
                ?>
            </select>
        </span>
        <span class="font-12 black advertise_tableTxt">
            Ad Type:<select id="ad_type" name="ad_type" class="InputBox" style="width: 100px;" maxlength="100">
            <option value="">All</option>
            <option value="text">Text</option>
            <option value="banner">Banner</option>
            <option value="thumbnail">Thumbnail</option>
            <option value="commercial break">Commercial Break</option>
            </select>
        </span>
        <span class="font-12 black advertise_tableTxt">
        Metric:
        <select id="adMetric" name="adMetric" class="InputBox" style="width: 150px;" maxlength="150">
            <option value="cpm" <?php echo $_POST['adMetric']=='cpm'?"selected=\"selected\" ":''; ?>>CPM</option>
            <option value="clk" <?php echo $_POST['adMetric']=='clk'?"selected=\"selected\" ":''; ?>>Clicks</option>
            <option value="ctr" <?php echo $_POST['adMetric']=='ctr'?"selected=\"selected\" ":''; ?>>CTR</option>
        </select>
        </span>
        <span class="font-12 black advertise_tableTxt">
            Date Range:
            <select id="adDateRange" name="adDateRange" class="InputBox" style="width: 150px;" maxlength="150">
                <option value="6" <?php if(isset($_POST['adDateRange'])){echo $_POST['adDateRange']=='6'?"selected=\"selected\" ":'';} ?>>Last 7 days</option>
                <option value="29" <?php if(isset($_POST['adDateRange'])){echo $_POST['adDateRange']=='29'?"selected=\"selected\" ":'';} ?>>Past 30 days</option>
                <option value="<?php echo date('F Y',time()); ?>" <?php if(isset($_POST['adDateRange'])){echo $_POST['adDateRange']==date('F Y',time())?"selected=\"selected\" ":'';} ?>><?php echo date('F Y',time()); ?></option>
            </select>
        </span>
    </td>
</tr>
<tr>
    <td>
    <span class="font-12 black advertise_tableTxt">
        Status:
        <select id="ad_status" name="ad_status" class="InputBox" style="width: 100px;" maxlength="100">
            <option value="">Current</option>
            <option value="ending">Ending</option>
            <option value="expired">Expired</option>
        </select>
    </span>
    <span class="font-12 black advertise_tableTxt">
        Purchase Type:
        <select id="purchase_type" name="purchase_type" class="InputBox" style="width: 100px;" maxlength="100">
            <option value="">All</option>
            <option value="direct">Direct</option>
            <option value="network">Network</option>
        </select>
    </span>    
    <span class="font-12 black advertise_tableTxt">
        <input type="submit" name="search_publisher_statistics" id="search_publisher_statistics" value="Generate" class="blank-button-big-add" />
    </span>
    </td>
</tr>
<?php
$today = date('Y-m-d');
$day=date('d');
$month=date('m');
$year=date('Y');
$last_month=$month-1;
$today_prev_month=$year."-".$last_month."-".$day;
?>
<?php
        function getDateRange(&$start_date, &$end_date, $days_num, $offset=0, $next=true) {
            $start_date = '';
            $end_date = '';
            $week = date('W');
            $week = $week - $offset;
            $date = date('Y-m-d');

            $i = 0;
            if($next){
                //GET NEXT 7 DAYS
                while(date('W', strtotime("-$i day")) >= $week) {
                    $start_date = date('Y-m-d', strtotime("-$i day"));
                    $i++;
                }
                list($yr, $mo, $da) = explode('-', $start_date);
                $end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da + $days_num, $yr));
            }
            else{
                //GET LAST 7 DAYS
                while(date('W', strtotime("-$i day")) >= $week) {
                $end_date = date('Y-m-d', strtotime("-$i day"));
                $i++;
                }
                list($yr, $mo, $da) = explode('-', $end_date);
                $start_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da - $days_num, $yr));
            }

        }

        function getMonthRange(&$start_date, &$end_date, $offset=0) {
        $start_date = '';
        $end_date = '';
        $date = date('Y-m-d');

        list($yr, $mo, $da) = explode('-', $date);
        $start_date = date('Y-m-d', mktime(0, 0, 0, $mo - $offset, 1, $yr));

        $i = 2;

        list($yr, $mo, $da) = explode('-', $start_date);

        while(date('d', mktime(0, 0, 0, $mo, $i, $yr)) > 1) {
        $end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $i, $yr));
        $i++;
        }
        }

        function createDateRangeArray($strDateFrom,$strDateTo,$dateFormat='d-m-Y') {
          // takes two dates formatted as YYYY-MM-DD and creates an
          // inclusive array of the dates between the from and to dates.
          $aryRange=array();

          $iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),     substr($strDateFrom,8,2),substr($strDateFrom,0,4));
          $iDateTo=mktime(1,0,0,substr($strDateTo,5,2),     substr($strDateTo,8,2),substr($strDateTo,0,4));

          if ($iDateTo>=$iDateFrom) {
            array_push($aryRange,date($dateFormat,$iDateFrom)); // first entry

            while ($iDateFrom<$iDateTo) {
              $iDateFrom+=86400; // add 24 hours
              array_push($aryRange,date($dateFormat,$iDateFrom));
            }
          }
          return $aryRange;
        }

        $sql_hit = "";
        $unitAd = "$";
        if(isset ($_POST['adMetric'])){
            $fAd = $_POST['adMetric'];
            if($_POST['adDateRange']==date('F Y',time())){
                getMonthRange($start, $end);
            }
            else{
                getDateRange($start, $end, $_POST['adDateRange'], 0, false); //get all days in month
            }
            switch ($fAd){
                case 'cpm':
                    $unitAd = "$";
                    $sql_hit = "select count(adsiteId) cnt, DATE_FORMAT(visit_time,'%W, %M %d, %Y') dt, DATE_FORMAT(visit_time,'%Y-%m-%d') sd from advertise_impression_trac
                                where visit_time between '$start 00:00:00' and '$end 23:59:59' and adsiteId=".$_POST['ad_site']." group by dt
                                order by sd desc";
                    break;
                case 'clk':
                    $unitAd = "clicks";
                    $sql_hit = "select count(adsiteId) cnt, DATE_FORMAT(click_time,'%W, %M %d, %Y') dt, DATE_FORMAT(click_time,'%Y-%m-%d') sd from advertise_click_trac
                                where click_time between '$start 00:00:00' and '$end 23:59:59' and adsiteId=".$_POST['ad_site']." group by dt
                                order by sd desc";
                    break;
                case 'ctr':
                    $unitAd = "%";
                    $sql_hit = "select count(adsiteId) cImp, DATE_FORMAT(visit_time,'%W, %M %d, %Y') dt, DATE_FORMAT(visit_time,'%Y-%m-%d') sd from advertise_impression_trac
                                where visit_time between '$start 00:00:00' and '$end 23:59:59' and adsiteId=".$_POST['ad_site']." group by dt
                                order by sd desc";
                    break;
                default:
                    break;
            }

        }
        else{
            getDateRange($start, $end, 6, 0, false); //get all days in week
            $sql_hit = "select count(adsiteId) cnt, DATE_FORMAT(visit_time,'%W, %M %d, %Y') dt, DATE_FORMAT(visit_time,'%Y-%m-%d') sd from advertise_impression_trac
                        where visit_time between '$start 00:00:00' and '$end 23:59:59' and adsiteId=$fAd group by dt order by sd desc";
        }
        $date_arr = createDateRangeArray($start,$end,'d F Y');
        $date_now = date('m-Y',time());
        $exe_query = mysql_query($sql_hit);

        //echo $sql_hit . '<br/>';
        //echo $start.'|'.$end .'<br/>';
        ?>
    <script src="JavaScripts/raphael.js" type="text/javascript" charset="utf-8"></script>
    <script src="JavaScripts/raphael.path.methods.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
        Raphael.fn.drawGrid = function (x, y, w, h, wv, hv, color) {
            color = color || "#000";
            var path = ["M", x, y, "L", x + w, y, x + w, y + h, x, y + h, x, y],
                rowHeight = h / hv,
                columnWidth = w / wv;
            for (var i = 1; i < hv; i++) {
                path = path.concat(["M", x, y + i * rowHeight, "L", x + w, y + i * rowHeight]);
            }
            for (var i = 1; i < wv; i++) {
                path = path.concat(["M", x + i * columnWidth, y, "L", x + i * columnWidth, y + h]);
            }
            return this.path(path.join(",")).attr({stroke: color});
        };

        $(function () {
            $("#data").css({
                position: "absolute",
                left: "-9999em",
                top: "-9999em"
            });
        });

        window.onload = function () {
            // Grab the data
            var labels = [],
                data = [];
            $("#data tfoot th").each(function () {
                labels.push($(this).html());
            });
            $("#data tbody td").each(function () {
                data.push($(this).html());
            });

            // Draw
            //var txtRpt = document.getElementById('tblReport');
            var width = 1000,
                height = 250,
                leftgutter = 0,
                bottomgutter = 20,
                topgutter = 10,
                colorhue = .6 || Math.random(),
                color = "hsb(" + [colorhue, 1, .75] + ")",
                r = Raphael("holder", width, height),
                txt = {font: '12px Fontin-Sans, Arial', fill: "#000"},
                txt1 = {font: '10px Fontin-Sans, Arial', fill: "#fff"},
                txt2 = {font: '12px Fontin-Sans, Arial', fill: "#000"},
                X = (width - leftgutter) / labels.length,
                max = Math.max.apply(Math, data),
                Y = (height - bottomgutter - topgutter) / max;
            r.drawGrid(leftgutter + X * .5, topgutter, width - leftgutter - X, height - topgutter - bottomgutter, 10, 10, "#333");
            var path = r.path().attr({stroke: color, "stroke-width": 4, "stroke-linejoin": "round"}),
                bgp = r.path().attr({stroke: "none", opacity: .3, fill: color}).moveTo(leftgutter + X * .5, height - bottomgutter),
                frame = r.rect(10, 10, 100, 40, 5).attr({fill: "#fff", stroke: "#474747", "stroke-width": 2}).hide(),
                label = [],
                is_label_visible = false,
                leave_timer,
                blanket = r.set();
            label[0] = r.text(60, 10, "hits").attr(txt).hide();
            label[1] = r.text(60, 40, "22 <?php echo $date_now;?>").attr(txt1).attr({fill: color}).hide();

            for (var i = 0, ii = labels.length; i < ii; i++) {
                var y = Math.round(height - bottomgutter - Y * data[i]),
                    x = Math.round(leftgutter + X * (i + .5)),
                    t = r.text(x, height - 6, labels[i].substring(0,2)).attr(txt).toBack();
                bgp[i == 0 ? "lineTo" : "cplineTo"](x, y, 10);
                path[i == 0 ? "moveTo" : "cplineTo"](x, y, 10);
                var dot = r.circle(x, y, 5).attr({fill: "#494fff", stroke: "#fff"});
                blanket.push(r.rect(leftgutter + X * i, 0, X, height - bottomgutter).attr({stroke: "none", fill: "#fff", opacity: 0}));
                var rect = blanket[blanket.length - 1];
                (function (x, y, data, lbl, dot) {
                    var timer, i = 0;
                    $(rect.node).hover(function () {
                        clearTimeout(leave_timer);
                        var newcoord = {x: +x + 7.5, y: y - 19};
                        if (newcoord.x + 100 > width) {
                            newcoord.x -= 114;
                        }
                        frame.show().animate({x: newcoord.x, y: newcoord.y}, 200 * is_label_visible);
                        //label[0].attr({text: data + " hit" + ((data % 10 == 1) ? "" : "s")}).show().animateWith(frame, {x: +newcoord.x + 50, y: +newcoord.y + 12}, 200 * is_label_visible);
                        label[0].attr({text: data + " <?php echo $unitAd; ?>"}).show().animateWith(frame, {x: +newcoord.x + 50, y: +newcoord.y + 12}, 200 * is_label_visible);
                        label[1].attr({text: lbl + ""}).show().animateWith(frame, {x: +newcoord.x + 50, y: +newcoord.y + 27}, 200 * is_label_visible);
                        dot.attr("r", 7);
                        is_label_visible = true;
                    }, function () {
                        dot.attr("r", 5);
                        leave_timer = setTimeout(function () {
                            frame.hide();
                            label[0].hide();
                            label[1].hide();
                            is_label_visible = false;
                            // r.safari();
                        }, 1);
                    });
                })(x, y, data[i], labels[i], dot);
            }
            bgp.lineTo(x, height - bottomgutter).andClose();
            frame.toFront();
            label[0].toFront();
            label[1].toFront();
            blanket.toFront();
        };
        </script>
<tr><td colspan="2">&nbsp;</td></tr>
<tr>
    <td colspan="2">
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td align="left" class="statsTitle">Summary Of Activity : <?php echo $start; ?> to <?php echo $end; ?></td>
        </tr>
        <tr>
        <td align="center">
        <!--    xxxxxxxx starts  -->
        <table width="100%" class="login_txt" cellspacing="1" cellpadding="0" border="0">
        <tr style="background-color:gray">
            <th class="listHeader" align="center" nowrap="true">
            <strong>Total Impressions:</strong>
            </th>
            <th class="listHeader" align="center" nowrap="true">
            Total Clicks
            </th>
            <th class="listHeader" align="center" nowrap="true">
            Average CTR:
            </th>
            <th class="listHeader" align="center" nowrap="true">
            Average CPC:
            </th>
            <th class="listHeader" align="center" nowrap="true">
            Total Cost:
            </th>
	    <?php
            if($num_summary>0){
                $class1="normalActive";
                $class2="normal";
                $class3="normal";
                $class4="white_sitename2";
            ?>
            <tr onmouseover="this.className='<?php echo $class1;?>'" onmouseout="this.className='<?php echo $class1;?>'" class="<?php echo $class1;?>">
            <?php
                $clickPerDay=0;
                $avgCPC=0;
                $rec=0;
		while($rec_details_summary=mysql_fetch_array($query_details_summary)){
	    ?>     
            <?php
            $sqlPrice_summary="select * FROM ".PRICE." where adspaceId='".$rec_details_summary[adspaceId]."' order by duration asc";
            $queryPrice_summary=mysql_query($sqlPrice_summary);
            $resultPrice_summary= mysql_fetch_array($queryPrice_summary);
            if($rec_details_summary[clickPerDay]==0){
                $clickPerDay_tot = 0;
                $avgCPC_tot = 0;
            }
            else{
                $clickPerDay_tot = $rec_details_summary[clickPerDay]*$resultPrice_summary[duration];
                $avgCPC_tot = '$'.number_format($resultPrice_summary[ammount]/$rec_details_summary[clickPerDay], 2, '.', '');
            }
            $clickPerDay=$clickPerDay+$clickPerDay_tot;
            $avgCPC=$avgCPC+$avgCPC_tot;
            ?>
            <?php
            if($rec_details[clickPerDay]>0){
                if($rec_details[clickPerDay]>$GLOBALS['avgImpression']){
                    $rec = $rec+number_format($rec_details_summary[clickPerDay]/$GLOBALS['avgImpression'], 2, '.', '');
                }
                else{
                    $rec=$rec+0;
                }
            }
            else{
                $rec=$rec+0;
            }
	}
            ?>
            <td class="<?php echo $class4;?>" align="left"><?php echo $rec;?></td>
            <td class="<?php echo $class4;?>" align="left"><?php echo $clickPerDay;?></td>
            <td class="<?php echo $class4;?>" align="left">0</td>
            <td class="<?php echo $class4;?>" align="left"><?php echo $clickPerDay;?></td>
            <td class="<?php echo $class4;?>" align="left"><?php echo $avgCPC;?>&nbsp;</td>
	</tr>
	<?php
        } // end if
	else{
	?>
	   <tr><td colspan="10" align="center" class="font-12 black advertise_tableTxt">No records found</td></tr>
	<?php
	}
	?>
        </table>
        <!-- xxxxxxxx ends  -->
    </td>
    </tr>
    </table>
    </td>
</tr>
<tr><td colspan="2">&nbsp;</td></tr>
    
<tr>
    <td>
        <table id="data">
        <tfoot style="display: block">
            <tr>
                <?php foreach ($date_arr as $vl) {?>
                    <th><?php echo $vl ?></th>
                <?php
                }
                ?>
            </tr>
        </tfoot>
        <tbody>
            <tr>
                <?php
                if(isset ($_POST['adMetric'])){
                    switch ($fAd){
                        case 'cpm':
                            while($cal_arr = mysql_fetch_array($exe_query)){
                                echo "<td>".round($cal_arr['cnt']/1000,3)."</td>";
                            }
                            break;
                        case 'clk':
                            while($cal_arr = mysql_fetch_array($exe_query)){
                                echo  "<td>".round($cal_arr['cnt'],3)."</td>";
                            }
                            break;
                        case 'ctr':
                            while($cal_arr = mysql_fetch_array($exe_query)){
                                $sql = "select count(adsiteId) cClik, DATE_FORMAT(click_time,'%W, %M %d, %Y') dt from advertise_click_trac
                                    where click_time between '".$cal_arr['sd']." 00:00:00' and '".$cal_arr['sd']." 23:59:59' and adsiteId=".$_POST['ad_site']." group by dt desc";
                                //echo $cal_arr['cImp'];die;
                                $ex = mysql_query($sql);
                                $cArr = mysql_fetch_array($ex);
                                echo "<td>".round($cArr[0]*100/$cal_arr['cImp'])."</td>";
                            }
                            break;
                        default:
                            break;
                    }
                }
                else{
                    while($cal_arr = mysql_fetch_array($exe_query)){
                        echo "<td>".round($cal_arr['cnt']/1000,3)."</td>";
                    }
                }
                ?>
            </tr>
        </tbody>
        </table>
        <div id="holder"></div>
    </td>

</tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr>
    <td colspan="2">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
    <td align="left" class="statsTitle">
        Daily Activity : <?php echo $start; ?> to <?php echo $end; ?>
    </td>
</tr>
<tr>
    <td align="center">
    <table width="100%" class="login_txt" cellspacing="1" cellpadding="0" border="0">
    <tr style="background-color:gray">	
	<th class="listHeader" align="center" nowrap="true">Impressions</th>
	<th class="listHeader" align="center" nowrap="true">Total Clicks</th>
	<th class="listHeader" align="center" nowrap="true">Average CPC</th>
	<th class="listHeader" align="center" nowrap="true">Average CTR</th>
	<th class="listHeader" align="center" nowrap="true">Total Cost</th>
        <?php
        if($num>0){
        $loop=0;
        while($rec_details=mysql_fetch_array($query_details)){
            $loop++;
            if($loop%2 == 0) {
                $class1="normalActive2";
                $class2="normal2";
                $class3="normal2";
                $class4="gray_sitename2";
            }
            else {
                $class1="normalActive";
                $class2="normal";
                $class3="normal";
                $class4="white_sitename2";
            }
        $sql_ad_space_type="select adspaceType from ".ADSPACEDETAILS." where adspaceId='".$rec_details['adspaceId']."'";
        $rec_ad_space_type=mysql_fetch_array(mysql_query($sql_ad_space_type));
        ?>
        <tr onmouseover="this.className='<?php echo $class1;?>'" onmouseout="this.className='<?php echo $class2;?>'" class="<?php echo $class3;?>">
        <?php
        $sqlPrice="select * FROM ".PRICE." where adspaceId='".$rec_details[adspaceId]."' order by duration asc";
        $queryPrice=mysql_query($sqlPrice);
        $resultPrice= mysql_fetch_array($queryPrice);
        if($rec_details[clickPerDay]==0){
            $clickPerDay = '*New';
            $avgCPC = '*New';
        }
        else{
            $clickPerDay = $rec_details[clickPerDay]*$resultPrice[duration];
            $avgCPC = '$'.number_format($resultPrice[ammount]/$rec_details[clickPerDay], 2, '.', '');
        }
        ?>
        <td class="<?php echo $class4;?>" align="left"><?php
        if($rec_details[clickPerDay]>0){
            if($rec_details[clickPerDay]>$GLOBALS['avgImpression']){
                echo $rec = number_format($rec_details[clickPerDay]/$GLOBALS['avgImpression'], 2, '.', '');
            }
            else{
                echo "0";
            }
        }
        else{
            echo "0";
        }
        ?>
        </td>
        <td class="<?php echo $class4;?>" align="left"><?php echo $clickPerDay;?></td>
        <td class="<?php echo $class4;?>" align="left"><?php echo $avgCPC;?>&nbsp;</td>
        <td class="<?php echo $class4;?>" align="left">0&nbsp;</td>
        <td class="<?php echo $class4;?>" align="left"><?php echo $rec_details['adPrice'];?></td>
        </tr>
	<?php
            }
	} // end if
	else
	{
	?>
	   <tr><TD colspan="10" align="center" class="font-12 black advertise_tableTxt">No records found</TD></tr>
	<?php
	}
	?>
        </table>
        </td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    <!-- ##########ends design ######## -->
    </td>
    </tr>
</table></td>
</tr>
<tr>
    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
    <td width="11"><img src="images/PinkBorderBottomLeft.jpg" alt="" width="11" height="11"></td>
    <td class="PinkBoxBottomBg"><img src="images/spacer.gif" alt="" width="10" height="11"></td>
    <td width="11"><img src="images/PinkBorderBottomRight.jpg" alt="" width="11" height="11"></td>
    </tr>
    </table></td>
    </tr>
</table></td>
<td>&nbsp;</td>
</tr>
</table></td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<?php
}
?>
